package pemks.dao;

import pemks.util.DBUtil;

import java.sql.*;

public class UserSecretDAO {
    // 保存用户私钥
    public boolean saveSK(String username, String sk) {
        String sql = "INSERT INTO user_secrets (username, sk) VALUES (?, ?) " +
                "ON DUPLICATE KEY UPDATE sk = VALUES(sk)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);
            pstmt.setString(2, sk);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            return false;
        }
    }

    // 获取用户私钥
    public String getSK(String username) {
        String sql = "SELECT sk FROM user_secrets WHERE username = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, username);
            ResultSet rs = pstmt.executeQuery();
            return rs.next() ? rs.getString("sk") : null;
        } catch (SQLException e) {
            return null;
        }
    }
}